/*
 * @Author: jianglijun1004 
 * @Date: 2020-03-10 03:47:27 
 * @Last Modified by: jianglijun
 * @Last Modified time: 2020-04-05 00:42:05
 */
const getRawBody = require('raw-body')
const util = require('./util')
const wechatMessage = require('./wechatMessage')
const crypto = require('crypto');
// const sha1 = require('sha1');
module.exports = (config, reply) => {
  return async (ctx, next) => {
    const method = ctx.method.toLowerCase(),
      {
        signature,
        timestamp,
        nonce,
        echostr,
        msg_signature
      } = ctx.query;
    const wechat_message = new wechatMessage({
      msg_signature,
      ...config
    });
    const tmpStr = wechat_message.genSign({
      timestamp,
      nonce
    })
    if (method === 'get') {
      if (tmpStr === signature) {
        ctx.body = echostr
      } else {
        ctx.status = 401
        ctx.body = 'Invalid signature'
      }
    } else if (method === 'post') {
      if (tmpStr !== signature) {
        return (ctx.body = 'Invalid signature')
      }
      const data = await getRawBody(ctx.req, {
        length: ctx.response.length,
        limit: '1mb',
        encoding: ctx.charset
      });
      const content = await util.parseXML(data);
      let message = util.formatMessage(content.xml);

      // 验证是否微信
      const sha1 = crypto.createHash('sha1');
      sha1.update([config.token, timestamp, nonce, message.Encrypt].sort().join(''));
      if (sha1.digest('hex') !== msg_signature) {
        ctx.body = '验证错误'
        return;
      }
      const extractMessage = wechat_message.decrypt(message.Encrypt);
      const fomatMessage = await util.parseXML(extractMessage);
      message = util.formatMessage(fomatMessage.xml)
      ctx.weixin = message;
      await reply.apply(ctx, [ctx, next]);
      const replyBody = ctx.body;
      let xml = util.tpl(replyBody, ctx.weixin);
      const msg_encrypt = wechat_message.encrypt(xml)
      const sha2 = crypto.createHash('sha1');
      sha2.update([config.token, timestamp, nonce, msg_encrypt].sort().join(''));
      xml = `
      <xml>
        <Encrypt><![CDATA[${msg_encrypt}]]></Encrypt>
        <MsgSignature><![CDATA[${sha2.digest('hex')}]]></MsgSignature>
        <TimeStamp>${timestamp}</TimeStamp>
        <Nonce><![CDATA[${nonce}]]></Nonce>
      </xml>
      `;
      console.log(xml);
      ctx.status = 200;
      ctx.response.type = 'application/xml';
      ctx.body = xml;
    }
  }
}
